package pdm.traj.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class StringUtil {
	
	public static String tailPath(String p) {
		if ((p.charAt(p.length() - 1) == '/' )|| (p.charAt(p.length() - 1) == '\\' )) {
			return tailPath(p.substring(0, p.length() - 1));
		} else {
			return p;
		}
	}
	
	public static void printStringList(List<String> list) {
		for (String str : list) {
			System.out.println(str);
		}
	}
	/**
	 * compare two date strings
	 * 
	 * @param d1
	 * @param d2
	 * @return 1 - d1 is new, -1 - d2 is new, 0 - same date  2 - wrong input
	 */
	public static int compareDateStr(String d1, String d2) {
		if (d1 == null || d2 == null || d1.length() == 0 || d2.length() == 0) {
			return 2;
		} else {
			int l = Math.min(d1.length(), d2.length());
			for (int i = 0; i < l; i++) {
				if (d1.charAt(i) > d2.charAt(i)) {
					return 1;
				} else if (d1.charAt(i) < d2.charAt(i)) {
					return -1;
				}
			}
			return 0;
		}
	}
	
	public static String beanToJson(Object obj)  {   
		// 这里异常都未进行处理，而且流的关闭也不规范。开发中请勿这样写，如果发生异常流关闭不了   
		ObjectMapper mapper = CommonUtil.getMapperInstance(false);   
		StringWriter writer = new StringWriter();   
		JsonGenerator gen;
		try {
			gen = new JsonFactory().createJsonGenerator(writer);
			mapper.writeValue(gen, obj);   
			gen.close();   
			String json = writer.toString();   
			writer.close();   
			return json;   
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
		return "error";
	} 
	
	public static Object  jsonToBean(String json, Class<?> cls) throws Exception {   
		ObjectMapper mapper = CommonUtil.getMapperInstance(false); 
		Object vo = mapper.readValue(json, cls);   
	    return vo;   
	}  

	public static void main(String[] args) {
		String p = "dksfjsdk/";
		String p2 = "dksfjsdk\\\\/";
		String p3 = "dksfjsdk\\\\//";
		System.out.println(tailPath(p));
		System.out.println(tailPath(p2));
		System.out.println(tailPath(p3));
	}
} 
